#include "public.h"
#include "Connection.h"
#include <iostream>
using namespace std;

Connection::Connection()
{
	_conn = mysql_init(nullptr);
}

Connection::~Connection()
{
	if (_conn != nullptr)
		mysql_close(_conn);
}

// 连接数据库
bool Connection::connect(string ip, unsigned short port,
						 string username, string password, string dbname)
{
	MYSQL *p = mysql_real_connect(_conn, ip.c_str(), username.c_str(),
								  password.c_str(), dbname.c_str(), port, nullptr, 0);
	return p != nullptr;
}

// 更新操作：insert、delete、update
bool Connection::update(string sql)
{
	if (mysql_query(_conn, sql.c_str()))
	{
		LOG("Update failed:" + sql);
		return false;
	}
	// else
	// {
	// 	cout << "Update Okay" << endl;
	// }
	return true;
}

MYSQL_RES *Connection::query(string sql)
{
	if (mysql_query(_conn, sql.c_str()))
	{
		LOG("Query failed:" + sql);
		return nullptr;
	}
	// else
	// 	cout << "Query Okay" << endl;
	return mysql_use_result(_conn);
}